<template>
  <section class="space-y-4 pb-16">
    <!-- 顶部工具条（卡片外）：左-场站筛选，右-场站数量统计 -->
    <div class="flex items-center justify-between">
      <!-- 场站筛选按钮（带小箭头） -->
      <div class="relative">
        <button @click="showPicker = !showPicker"
                class="inline-flex items-center gap-1 px-3 py-1.5 border border-gray-200 bg-white/80 backdrop-blur rounded-md text-sm text-gray-700 hover:bg-white shadow-sm">
          <span class="truncate max-w-[180px]">{{ selectedSite ? selectedSite.stationName : '全部场站' }}</span>
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-4 h-4 text-gray-500"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 9l6 6 6-6"/></svg>
        </button>
        <!-- 场站下拉选择 -->
        <div v-if="showPicker" class="absolute left-0 top-full mt-2 z-20 inline-block rounded-lg bg-white text-gray-900 shadow-lg ring-1 ring-black/5 max-h-[12rem] overflow-y-auto">
          <button class="block text-left px-3 py-2 hover:bg-gray-50 text-sm whitespace-nowrap" @click="selectSite(null)"><span class="truncate max-w-[16rem]" title="全部场站">全部场站</span></button>
          <div>
            <button v-for="s in sites" :key="s.stationId" class="block text-left px-3 py-2 hover:bg-gray-50 text-sm whitespace-nowrap" @click="selectSite(s.stationId)">
              <span class="truncate max-w-[16rem]" :title="s.stationName">{{ s.stationName }}</span>
            </button>
          </div>
        </div>
      </div>
      <!-- 场站数量统计 -->
      <div class="text-sm text-gray-500">共 {{ displaySiteCount }} 个</div>
    </div>

    <!-- 总览卡片 -->
    <div class="relative overflow-hidden rounded-2xl bg-gradient-to-br from-brand-500 to-indigo-600 text-white shadow-glass">
      <div class="absolute inset-0 bg-[radial-gradient(40%_60%_at_80%_20%,rgba(255,255,255,0.22),transparent)]"></div>

      <div class="p-5 relative">
        <div class="flex items-center justify-between">
          <div>
            <div class="text-base text-white/80">{{ isToday ? '今日' : '昨日' }} 实际收入</div>
            <div class="mt-1 text-3xl font-extrabold">¥ {{ formatValue(displaySummary.actualFee) }}</div>
          </div>
          <!-- 切换按钮 -->
          <div class="bg-white/15 backdrop-blur-md rounded-full p-1 flex items-center gap-1">
            <button @click="toggleDay(true)" class="px-3 py-1.5 rounded-full text-sm font-medium"
                    :class="isToday ? 'bg-white text-brand-700' : 'text-white/90'">今日</button>
            <button @click="toggleDay(false)" class="px-3 py-1.5 rounded-full text-sm font-medium"
                    :class="!isToday ? 'bg-white text-brand-700' : 'text-white/90'">昨日</button>
          </div>
        </div>

        <div class="mt-5 grid grid-cols-2 gap-3">
          <div class="rounded-xl bg-white/12 p-3">
            <div class="text-white/80 text-lg">总服务费</div>
            <div class="mt-1 text-xl font-medium truncate">¥{{ formatValue(displaySummary.serviceFee) }}</div>
          </div>
          <div class="rounded-xl bg-white/12 p-3">
            <div class="text-white/80 text-lg">分成比例</div>
            <div class="mt-1 text-xl font-medium truncate">{{ formatShareRatio(displaySummary.shareRatio) }}</div>
          </div>
          <div class="rounded-xl bg-white/12 p-3">
            <div class="text-white/80 text-lg">订单数量</div>
            <div class="mt-1 text-xl font-medium truncate">{{ displaySummary.orders }}</div>
          </div>
          <div class="rounded-xl bg-white/12 p-3">
            <div class="text-white/80 text-lg">其他费用</div>
            <div class="mt-1 text-xl font-medium truncate">¥{{ formatValue(displaySummary.otherFee) }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 导航栏 + 内容区 -->
    <div class="rounded-2xl bg-white shadow-sm border border-gray-100 overflow-visible mb-24">
      <!-- 顶部导航标签 -->
      <div class="px-3 py-2 border-b border-gray-100">
        <div class="flex items-center justify-center gap-2">
          <button @click="setTab('calendar')" :class="tabBtn('calendar')" class="px-3 py-1.5 rounded-full text-sm">经营日历</button>
          <button @click="setTab('trend')" :class="tabBtn('trend')" class="px-3 py-1.5 rounded-full text-sm">收入趋势</button>
        </div>
      </div>
      <!-- 面板内容 -->
      <div class="p-4">
        <!-- 经营日历：真实月历（周一至周日），左上显示年月，右侧显示 日均 与 总计 -->
        <div v-if="navTab==='calendar'">
          <!-- 头部：年月与统计、月份切换 -->
          <div class="flex items-center justify-between mb-3">
            <div class="flex items-center gap-2">
              <button @click="prevMonth" class="p-1 rounded hover:bg-gray-100 text-gray-500" aria-label="上个月">
                <svg viewBox="0 0 24 24" class="w-6 h-6"><path fill="currentColor" d="M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>
              </button>
              <div class="text-sm font-medium text-gray-900">{{ monthTitle }}</div>
              <button @click="nextMonth" class="p-1 rounded hover:bg-gray-100 text-gray-500" aria-label="下个月">
                <svg viewBox="0 0 24 24" class="w-6 h-6"><path fill="currentColor" d="M8.59 16.59 13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg>
              </button>
            </div>
            <div class="text-xs text-gray-600 text-left">
              <div class="flex items-baseline gap-0 leading-none">
                <span class="text-gray-500">日均：</span>
                <span class="text-gray-900 font-medium tracking-tight ml-0.5">{{ monthAvg }} 元</span>
              </div>
              <div class="flex items-baseline gap-0 mt-1 leading-none">
                <span class="text-gray-500">总计：</span>
                <span class="text-gray-900 font-medium tracking-tight ml-0.5">{{ monthTotal }} 元</span>
              </div>
            </div>
          </div>

          <!-- 表头（周一~周日） -->
          <div class="grid grid-cols-7 gap-2 text-[11px] text-gray-400 mb-1">
            <div class="text-center">周一</div>
            <div class="text-center">周二</div>
            <div class="text-center">周三</div>
            <div class="text-center">周四</div>
            <div class="text-center">周五</div>
            <div class="text-center">周六</div>
            <div class="text-center">周日</div>
          </div>
          <!-- 月历网格：7 列（周一到周日），带热力背景（值不显示） -->
          <div class="grid grid-cols-7 gap-2">
            <button v-for="cell in monthGrid" :key="cell.key" :disabled="!cell.inMonth" @click="cell.inMonth && selectDay(cell.day)"
                    class="aspect-square rounded-lg p-1 relative border transition duration-150 ease-out transform disabled:opacity-50 overflow-hidden"
                    :class="cellClass(cell)">
              <!-- 热力背景块：根据热度透明度叠加，值不展示 -->
              <div v-if="cell.inMonth" class="absolute inset-0" :style="heatStyle(cell.day)"></div>
              <div class="w-full h-full grid place-items-center relative">
                <div class="text-sm font-semibold" :class="cell.inMonth ? (selectedDay===cell.day ? 'text-brand-900 text-lg font-extrabold' : 'text-gray-900') : 'text-gray-300'">
                  {{ cell.day || '' }}
                </div>
              </div>
            </button>
          </div>

          <!-- 选中日期详情：常驻显示，标题与说明居中，日期颜色更深 -->
          <div class="mt-4 mb-6 rounded-xl border border-gray-100 bg-gray-50 p-3">
            <div class="text-center">
              <div class="text-base font-semibold text-gray-900">{{ selectedDateTitle }}</div>
              <div class="text-[11px] text-gray-500 mt-0.5">--按结算时间统计--</div>
            </div>
            <div class="mt-3 grid grid-cols-2 gap-2 text-sm">
              <div class="rounded-lg bg-white border border-gray-100 p-3">
                <div class="text-xs text-gray-500">总服务费</div>
                <div class="mt-1 font-semibold text-gray-900">{{ fmt(selectedStats.totalServiceFee) }}</div>
              </div>
              <div class="rounded-lg bg-white border border-gray-100 p-3">
                <div class="text-xs text-gray-500">实际收入</div>
                <div class="mt-1 font-semibold text-gray-900">{{ fmt(selectedStats.actualIncome) }}</div>
              </div>
              <div class="rounded-lg bg-white border border-gray-100 p-3">
                <div class="text-xs text-gray-500">订单数量</div>
                <div class="mt-1 font-semibold text-gray-900">{{ selectedStats.orders }}</div>
              </div>
              <div class="rounded-lg bg-white border border-gray-100 p-3">
                <div class="text-xs text-gray-500">其他费用</div>
                <div class="mt-1 font-semibold text-gray-900">{{ fmt(selectedStats.otherFee) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 收入趋势：ECharts 大号折线图 -->
        <div v-else>
          <div class="w-full">
            <!-- 趋势月份切换置于图上方，右侧显示单位：元 -->
            <div class="mb-2 flex items-center justify-between gap-2 text-sm text-gray-700">
              <div class="flex items-center gap-2">
                <button @click="prevTrendMonth" class="p-1 rounded hover:bg-gray-100 text-gray-500" aria-label="上个月">
                  <svg viewBox="0 0 24 24" class="w-6 h-6"><path fill="currentColor" d="M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>
                </button>
                <div class="text-sm font-medium text-gray-900">{{ trendMonthTitle }}</div>
                <button @click="nextTrendMonth" class="p-1 rounded hover:bg-gray-100 text-gray-500" aria-label="下个月">
                  <svg viewBox="0 0 24 24" class="w-6 h-6"><path fill="currentColor" d="M8.59 16.59 13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg>
                </button>
              </div>
              <div class="text-xs text-gray-500 pr-1 select-none">单位：元</div>
            </div>
            <div ref="trendRef" class="w-full h-[20rem]" :style="{minHeight: '300px'}"></div>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { computed, ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getHomeSummary, getCalendarSummary, getIncomeTrend } from '../api/home'
import { getSimpleStationList } from '../api/station'
import { getDictionary } from '../api/dictionary'

// 站点数据
const sites = ref([])
const totalSites = ref(0)
const loading = ref(false)

// 字典数据
const dictionaryData = ref({})

// 场站筛选
const showPicker = ref(false)
const selectedSiteId = ref(null)
const selectedSite = computed(() => sites.value?.find(s => s.stationId === selectedSiteId.value) || null)
// 显示站点数量：全部场站显示total，选择具体场站显示1
const displaySiteCount = computed(() => {
  return selectedSiteId.value ? 1 : totalSites.value || 0
})
const selectSite = (id) => { 
  selectedSiteId.value = id; 
  showPicker.value = false
  console.log('选择站点:', id, '站点名称:', id ? sites.value?.find(s => s.stationId === id)?.stationName : '全部场站')
  // 选择站点后重新加载汇总数据
  loadSummaryData()
}

// 今日/昨日切换
const isToday = ref(true)
const toggleDay = async (today) => {
  isToday.value = today
  await loadSummaryData()
}

// 汇总数据
const summaryData = ref({})

// 加载字典数据
const loadDictionary = async () => {
  try {
    console.log('开始加载字典数据...')
    const response = await getDictionary()
    if (response.success) {
      dictionaryData.value = response.data || {}
      console.log('字典数据加载成功:', dictionaryData.value)
      
      // 将字典数据保存到本地存储，方便其他页面使用
      localStorage.setItem('h5_dictionary', JSON.stringify(dictionaryData.value))
    } else {
      console.error('加载字典数据失败:', response.message)
      dictionaryData.value = {}
    }
  } catch (error) {
    console.error('加载字典数据失败:', error)
    dictionaryData.value = {}
  }
}

// 加载站点列表
const loadStations = async () => {
  try {
    loading.value = true
    const response = await getSimpleStationList()
    if (response.success) {
      // 后端返回的是 SimpleStationPage 对象，包含 list 和 total 字段
      sites.value = response.data?.list || []
      totalSites.value = response.data?.total || 0
      console.log('站点列表加载成功:', sites.value, '总站点数:', totalSites.value)
    } else {
      console.error('加载站点列表失败:', response.message)
      sites.value = []
      totalSites.value = 0
    }
  } catch (error) {
    console.error('加载站点列表失败:', error)
    sites.value = []
    totalSites.value = 0
  } finally {
    loading.value = false
  }
}

// 加载汇总数据
const loadSummaryData = async () => {
  try {
    const params = {
      dateType: isToday.value ? '1' : '0'
    }
    if (selectedSiteId.value) {
      params.stationId = selectedSiteId.value
    }
    
    console.log('请求汇总数据参数:', params)
    const response = await getHomeSummary(params)
    if (response.success) {
      summaryData.value = response.data || {}
      console.log('汇总数据加载成功:', summaryData.value)
    } else {
      console.error('加载汇总数据失败:', response.message)
      summaryData.value = {}
    }
  } catch (error) {
    console.error('加载汇总数据失败:', error)
    summaryData.value = {}
  }
}

// 点击外部区域关闭下拉菜单
const closePickerOnOutsideClick = (event) => {
  const pickerElement = event.target.closest('.relative')
  if (!pickerElement && showPicker.value) {
    showPicker.value = false
  }
}

// 监听点击事件
onMounted(() => {
  document.addEventListener('click', closePickerOnOutsideClick)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closePickerOnOutsideClick)
})

// 数值格式化函数 - 只在超出长度时缩写
const formatValue = (value) => {
  const num = Number(value || 0)
  
  // 首先尝试显示完整数值
  let fullValue = ''
  if (num >= 100) {
    fullValue = num.toFixed(0)
  } else {
    fullValue = num.toFixed(2)
  }
  
  // 检查完整数值是否可能超出容器宽度（假设容器宽度大约能显示8-10个字符）
  // 对于金额，加上¥符号和可能的千分位分隔符
  const displayLength = fullValue.length + 1 // +1 for ¥ symbol
  
  // 如果完整数值可能超出显示范围，才进行缩写
  if (displayLength > 10) {
    if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + 'M'
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'k'
    }
  }
  
  // 否则显示完整数值
  return fullValue
}

// 分成比例格式化函数（后端返回的已经是带%的格式）
const formatShareRatio = (ratios) => {
  if (!ratios || ratios.length === 0) return '80%'
  if (typeof ratios === 'string') return ratios
  if (Array.isArray(ratios)) {
    if (ratios.length === 1) return ratios[0]
    return ratios.join('/')
  }
  return '80%'
}

// 展示摘要（平台/场站）
const displaySummary = computed(() => {
  const data = summaryData.value
  console.log('当前汇总数据:', data)
  
  // 处理分成比例，确保有有效值
  let shareRatio = data.shareRatio
  if (!shareRatio) {
    shareRatio = '0%' // 默认值
  }
  
  return {
    actualFee: Number(data.actualFee || 0),
    serviceFee: Number(data.serviceFee || 0),
    otherFee: Number(data.otherFee || 0),
    orders: Number(data.orders || 0),
    shareRatio: shareRatio
  }
})
// 首页下方导航与示例数据
const navTab = ref('calendar')
const tabBtn = (k) => navTab.value === k ? 'bg-brand-600 text-white' : 'bg-gray-100 text-gray-700'
const setTab = (k) => { 
  navTab.value = k; 
}

// 经营日历：按月份构造真实月历（周一~周日），调用后端接口获取数据
const monthOffset = ref(0) // 0=本月，-1=上月，+1=下月
const targetDate = computed(() => {
  const d = new Date()
  d.setDate(1)
  d.setMonth(d.getMonth() + monthOffset.value)
  return d
})
const monthTitle = computed(() => `${targetDate.value.getFullYear()}年${targetDate.value.getMonth()+1}月`)
const daysInMonth = computed(() => new Date(targetDate.value.getFullYear(), targetDate.value.getMonth()+1, 0).getDate())
// JS 的 getDay() 周日=0，这里把周一设为一周起点
const firstDayWeek = computed(() => {
  const w = new Date(targetDate.value.getFullYear(), targetDate.value.getMonth(), 1).getDay()
  return (w === 0 ? 7 : w) // 周一=1 ... 周日=7
})

// 月份汇总数据
const monthSummaryData = ref(null)
const monthDaily = computed(() => {
  if (!monthSummaryData.value) {
    return Array.from({ length: daysInMonth.value }, (_,i) => ({
      day: (i+1).toString().padStart(2, '0'),
      isToday: false,
      hasData: false,
      totalServiceFee: 0,
      actualIncome: 0,
      orders: 0,
      otherFee: 0
    }))
  }
  return monthSummaryData.value.list || []
})

const monthTotal = computed(() => monthSummaryData.value ? Number(monthSummaryData.value.monthTotal) : 0)
const monthAvg = computed(() => monthSummaryData.value ? Number(monthSummaryData.value.dayAvg) : 0)
const isCurrentMonth = computed(() => monthSummaryData.value ? monthSummaryData.value.isCurrentMonth : false)

const monthGrid = computed(() => {
  const cells = []
  const lead = firstDayWeek.value - 1
  const totalCells = Math.ceil((lead + daysInMonth.value) / 7) * 7
  
  for (let i=0; i<totalCells; i++) {
    const day = i - lead + 1
    const inMonth = day >= 1 && day <= daysInMonth.value
    const dayStr = day.toString().padStart(2, '0')
    const dayData = monthDaily.value.find(d => d.day === dayStr) || {
      day: dayStr,
      isToday: false,
      hasData: false,
      totalServiceFee: 0,
      actualIncome: 0,
      orders: 0,
      otherFee: 0
    }
    
    cells.push({
      key: `${monthTitle.value}-${i}`,
      day: inMonth ? day : '',
      inMonth,
      data: dayData
    })
  }
  return cells
})

// 加载月份汇总数据
const loadMonthSummary = async () => {
  try {
    const year = targetDate.value.getFullYear().toString()
    const month = (targetDate.value.getMonth() + 1).toString().padStart(2, '0')
    
    const params = {
      year: year,
      month: month
    }
    
    if (selectedSiteId.value) {
      params.stationId = selectedSiteId.value
    }
    
    console.log('请求月份汇总数据参数:', params)
    const response = await getCalendarSummary(params)
    if (response.success) {
      monthSummaryData.value = response.data || {}
      console.log('月份汇总数据加载成功:', monthSummaryData.value)
    } else {
      console.error('加载月份汇总数据失败:', response.message)
      monthSummaryData.value = null
    }
  } catch (error) {
    console.error('加载月份汇总数据失败:', error)
    monthSummaryData.value = null
  }
}

const prevMonth = () => { 
  monthOffset.value -= 1; 
  selectedDay.value = 1;
  loadMonthSummary()
}
const nextMonth = () => { 
  monthOffset.value += 1; 
  selectedDay.value = 1;
  loadMonthSummary()
}

// 日历格样式（根据是否有数据显示不同颜色）
const selectedDay = ref(1)
const selectDay = (d) => { 
  if (d && d >= 1 && d <= daysInMonth.value) {
    selectedDay.value = d
  }
}
const cellClass = (cell) => {
  if (!cell.inMonth) return 'bg-gray-50 text-gray-300 border-gray-100 cursor-default'
  
  const dayData = cell.data
  const hasData = dayData?.hasData || false
  const isSelected = selectedDay.value === cell.day
  
  if (isSelected) {
    return 'bg-brand-100 border-brand-300 ring-2 ring-brand-400 shadow-md scale-[1.02]'
  } else if (hasData) {
    return 'bg-green-50 hover:bg-green-100 border-green-200 hover:shadow-sm'
  } else {
    return 'bg-white hover:bg-gray-50 border-gray-100 hover:shadow-sm'
  }
}
// 热力背景样式：根据实际收入数据设置透明度
const heatStyle = (day) => {
  const dayData = monthDaily.value.find(d => d.day === day.toString().padStart(2, '0'))
  const v = dayData?.actualIncome ?? 0
  
  if (v === 0) return 'background: transparent'
  
  // 非线性增强对比度：缩放到 0~1 后做次方提升差异
  const scale = 300 // 调整刻度让颜色更明显
  const r = Math.max(0, Math.min(1, v / scale))
  const ratio = Math.pow(r, 0.6) // 0.6 次方提升亮度
  const alpha = 0.15 + ratio * 0.5 // 0.15~0.65 的透明度，更明显
  return `background: rgba(16, 185, 129, ${alpha})`
}

// 选中日期详情
const selectedDateTitle = computed(() => `${targetDate.value.getFullYear()}年${targetDate.value.getMonth()+1}月${selectedDay.value}日`)
const selectedStats = computed(() => {
  const dayStr = selectedDay.value.toString().padStart(2, '0')
  const d = monthDaily.value.find(item => item.day === dayStr)
  return d || { 
    totalServiceFee: 0, 
    actualIncome: 0, 
    orders: 0, 
    otherFee: 0,
    hasData: false,
    isToday: false
  }
})
const fmt = (n) => Number(n || 0).toFixed(2)

// 收入趋势数据
const trendData = ref(null)
const trendRef = ref(null)
let trendChart = null

// 收入趋势独立的月份控制
const trendMonthOffset = ref(0)
const trendTargetDate = computed(() => {
  const d = new Date()
  d.setDate(1)
  d.setMonth(d.getMonth() + trendMonthOffset.value)
  return d
})
const trendMonthTitle = computed(() => `${trendTargetDate.value.getFullYear()}年${trendTargetDate.value.getMonth()+1}月`)
const trendDaysInMonth = computed(() => new Date(trendTargetDate.value.getFullYear(), trendTargetDate.value.getMonth()+1, 0).getDate())

// 加载收入趋势数据
const loadTrendData = async () => {
  try {
    const year = trendTargetDate.value.getFullYear().toString()
    const month = (trendTargetDate.value.getMonth() + 1).toString().padStart(2, '0')
    
    const params = {
      year: year,
      month: month
    }
    
    if (selectedSiteId.value) {
      params.stationId = selectedSiteId.value
    }
    
    console.log('请求收入趋势数据参数:', params)
    const response = await getIncomeTrend(params)
    if (response.success) {
      trendData.value = response.data || {}
      console.log('收入趋势数据加载成功:', trendData.value)
      renderTrend()
    } else {
      console.error('加载收入趋势数据失败:', response.message)
      trendData.value = null
    }
  } catch (error) {
    console.error('加载收入趋势数据失败:', error)
    trendData.value = null
  }
}

// 趋势数据格式化
const trendDays = computed(() => {
  if (!trendData.value || !trendData.value.list) {
    // 如果没有数据，返回当月所有天数
    return Array.from({ length: trendDaysInMonth.value }, (_, i) => i + 1)
  }
  
  // 创建一个包含当月所有天数的数组
  const allDays = Array.from({ length: trendDaysInMonth.value }, (_, i) => i + 1)
  
  // 将后端返回的数据映射到对应的天数
  return allDays.map(day => {
    // 查找当天是否有数据
    const dayData = trendData.value.list.find(item => {
      // 假设后端返回的日期格式是 "2025-11-01" 或 "11-01"
      const dateParts = item.date.split('-')
      const itemDay = parseInt(dateParts[dateParts.length - 1])
      return itemDay === day
    })
    
    return day
  })
})

const trendSeries = computed(() => {
  if (!trendData.value || !trendData.value.list) {
    return Array.from({ length: trendDaysInMonth.value }, () => 0)
  }
  
  // 创建一个包含当月所有天数的收入数据数组
  const allDays = Array.from({ length: trendDaysInMonth.value }, (_, i) => i + 1)
  
  return allDays.map(day => {
    // 查找当天是否有数据
    const dayData = trendData.value.list.find(item => {
      const dateParts = item.date.split('-')
      const itemDay = parseInt(dateParts[dateParts.length - 1])
      return itemDay === day
    })
    
    return dayData ? Number(dayData.actualIncome || 0) : 0
  })
})

// 收入趋势月份切换函数
const prevTrendMonth = () => { 
  trendMonthOffset.value -= 1
}
const nextTrendMonth = () => { 
  trendMonthOffset.value += 1
}

const buildTrendOption = () => {
  const year = trendTargetDate.value.getFullYear()
  const month = String(trendTargetDate.value.getMonth() + 1).padStart(2, '0')
  
  return {
    grid: { left: 28, right: 8, top: 10, bottom: 36 },
    tooltip: { 
      trigger: 'axis',
      triggerOn: 'mousemove|click',
      backgroundColor: 'rgba(17,24,39,0.95)',
      borderRadius: 10,
      padding: [10, 12],
      textStyle: { color: '#fff', fontSize: 13, lineHeight: 18 },
      extraCssText: 'box-shadow: 0 6px 24px rgba(0,0,0,0.18);',
      formatter: (params) => {
        const p = Array.isArray(params) ? params[0] : params
        const day = Number(p.axisValue)
        const d = String(day).padStart(2, '0')
        const dateStr = `${year}-${month}-${d}`
        const val = Number(p.data || 0).toFixed(2)
        const color = (p.color && typeof p.color === 'string') ? p.color : 'rgb(16,185,129)'
        
        // 获取当天的完整数据
        const dayData = trendData.value?.list?.find(item => {
          const dateParts = item.date.split('-')
          const itemDay = parseInt(dateParts[dateParts.length - 1])
          return itemDay === day
        })
        
        const row1 = `<span style="display:inline-flex;align-items:center;gap:8px;">`
          + `<span style="display:inline-block;width:12px;height:12px;border-radius:50%;background:${color};border:3px solid #ffffff;"></span>`
          + `<span>实际收入&nbsp;&nbsp;${val} 元</span>`
          + `</span>`
        
        const otherFee = Number(dayData?.otherFee || 0).toFixed(2)
        const row2 = `<span style="display:inline-flex;align-items:center;gap:8px;">`
          + `<span style="display:inline-block;width:12px;height:12px;border-radius:50%;background:#9CA3AF;border:3px solid #ffffff;"></span>`
          + `<span>其他费用&nbsp;&nbsp;${otherFee} 元</span>`
          + `</span>`
        
        const orders = dayData?.orders || 0
        const row3 = `<span style="display:inline-flex;align-items:center;gap:8px;">`
          + `<span style="display:inline-block;width:12px;height:12px;border-radius:50%;background:#F59E0B;border:3px solid #ffffff;"></span>`
          + `<span>订单数量&nbsp;&nbsp;${orders} 单</span>`
          + `</span>`
        
        return `${dateStr}<br/>${row1}<br/>${row2}<br/>${row3}`
      }
    },
    xAxis: { 
      type: 'category', 
      data: trendDays.value,
      boundaryGap: false,
      axisLine: { lineStyle: { color: '#D1D5DB' } }, 
      axisTick: { alignWithLabel: true },
      axisLabel: { 
        color: '#6B7280', 
        fontSize: 11, 
        interval: 0, 
        formatter: (val) => {
          const day = Number(val)
          // 只显示1、7、14、21、28日
          if ([1, 7, 14, 21, 28].includes(day)) {
            return `${day}日`
          }
          return ''
        }
      }
    },
    yAxis: { 
      type: 'value', 
      axisLine: { show: false }, 
      splitLine: { lineStyle: { color: '#E5E7EB' } }, 
      axisLabel: { color: '#6B7280', fontSize: 11 } 
    },
    dataZoom: [{ type: 'inside', start: 0, end: 100 }],
    series: [{ 
      type: 'line', 
      data: trendSeries.value, 
      smooth: true, 
      symbol: 'circle', 
      symbolSize: 6,
      lineStyle: { width: 3.2, color: 'rgb(16,185,129)' }, 
      itemStyle: { color: 'rgb(16,185,129)', borderColor: '#fff', borderWidth: 2 }, 
      areaStyle: { color: 'rgba(16,185,129,0.12)' } 
    }]
  }
}
const renderTrend = async () => {
  await nextTick()
  if (!trendRef.value) return
  try {
    // DOM 变更或首次进入时，安全重建实例
    if (!trendChart || (trendChart.getDom && trendChart.getDom() !== trendRef.value)) {
      if (trendChart) { try { trendChart.dispose() } catch (e) {} }
      trendChart = echarts.init(trendRef.value)
    }
    trendChart.setOption(buildTrendOption(), true)
    requestAnimationFrame(() => trendChart && trendChart.resize())
  } catch (error) {
    console.error('ECharts渲染失败:', error)
  }
}
watch(() => navTab.value, async (v)=>{
  console.log('Tab切换:', v)
  if (v==='trend') { 
    await nextTick(); 
    console.log('切换到收入趋势，加载数据...')
    loadTrendData()
  }
  else if (v==='calendar') { 
    await nextTick(); 
    console.log('切换到经营日历，重新加载数据...')
    loadMonthSummary()
  }
  else { if (trendChart) { try { trendChart.dispose() } catch(e) {} trendChart = null } }
})
watch(() => trendMonthOffset.value, async ()=>{ 
  if (navTab.value==='trend') { 
    await nextTick(); 
    loadTrendData()
  } 
})
onMounted(async () => {
  // 初始化加载数据
  await loadDictionary() // 首先加载字典数据
  await loadStations()
  await loadSummaryData()
  await loadMonthSummary()
  
  if (navTab.value==='trend') { 
    await nextTick(); 
    loadTrendData()
  }
  const onResize = () => { if (navTab.value==='trend') renderTrend() }
  window.addEventListener('resize', onResize)
})
onBeforeUnmount(() => { if (trendChart) trendChart.dispose(); window.removeEventListener('resize', renderTrend) })


</script>